package org.springframework.boot.dcj.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.dcj.config.UserConfig;
import org.springframework.boot.dcj.feign.OrderClient;
import org.springframework.boot.dcj.service.CommonService;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class TestController {
    @Resource
    UserConfig userConfig;
    @Resource
    OrderClient orderClient;
    @Resource
    CommonService commonService;
    @Resource
    RestTemplate restTemplate;
    @Resource
    JdbcClient jdbcClient;
    @Resource
    ApplicationContext applicationContext;

    @GetMapping("/info")
    // @SentinelResource 注解用来标识资源是否被限流、降级
    @SentinelResource(value = "info", blockHandler = "blockHandler", fallback = "fallback")
    public String getUser() {
        System.out.println(userConfig.toString());
        return userConfig.toString();
    }



    @GetMapping("/sentinelResourceAspect")
    public String sentinelResourceAspect() {
        return commonService.sentinelResourceAspect();
    }


    // 自己配置熔断规则,比如异常数
    @SentinelResource(value = "hystrix", fallback = "fallback")
    @GetMapping("/hystrix")
    public String hystrix() {
        throw new UnsupportedOperationException();
    }
    // 限流与阻塞处理
    public String blockHandler(BlockException ex) {
        return "限流了";
    }
    // 熔断处理
    public String fallback() {
        return "熔断了";
    }



    @GetMapping("/orderInfo")
    public String getOrderInfo() {
        return orderClient.getOrder();
    }

    @GetMapping("/restTemplateCall")
    public String restTemplateCall() {
        // 为什么使用服务名才能访问? -- @LoadBalanced,他默认按照服务名进行负载均衡请求了
        return restTemplate.getForObject("http://order/order/info", String.class);
    }


    @GetMapping("/findAll")
    public String findAll() {
        JdbcClient.StatementSpec sql = jdbcClient.sql("select * from test");
        JdbcClient.MappedQuerySpec<TestBean> query = sql.query(TestBean.class);
        List<TestBean> list = query.list();
        return list.toString();
    }

    @Data
    public static class TestBean {
        private Long id;
        private String name;
    }
}
